#include "VerticalSingleLineDrawer.h"
#include <QPen>
#include <QGraphicsScene>
#include <QDebug>
#include <QtMath>
#include "../Common/DraggableLineItem.h"

// 包含MeasurementMode的定义
#include "MeasurementAlgorithmBase.h"

VerticalSingleLineDrawer::VerticalSingleLineDrawer(QObject *parent) 
    : QObject(parent),
      m_scene(nullptr),
      m_lineItem(nullptr),
      m_imageWidth(0),
      m_imageHeight(0),
      m_scale(1.0),
      m_offset(QPointF())
{
    initializeStyles();
}

VerticalSingleLineDrawer::~VerticalSingleLineDrawer()
{
    clearAll();
}

void VerticalSingleLineDrawer::setScene(QGraphicsScene *scene)
{
    if (m_scene != scene) {
        // 清除之前场景中的绘制项
        clearAll();
        m_scene = scene;
    }
}

void VerticalSingleLineDrawer::initializeLine(int imageWidth, int imageHeight, double scale, const QPointF &offset)
{
    if (!m_scene) {
        qWarning() << "场景未设置，无法初始化线"; 
        return;
    }

    // 保存图像参数
    m_imageWidth = imageWidth;
    m_imageHeight = imageHeight;
    m_scale = scale;
    m_offset = offset;

    // 清除之前的绘制项
    removeAllItems();

    int x=imageWidth / 2;
    // 计算线的起始和结束点（图像坐标）
    int startY = 0;
    int endY = imageHeight;
    
    // 转换为场景坐标
    QPointF startScene = imageToSceneCoordinates(QPointF(x, startY));
    QPointF endScene = imageToSceneCoordinates(QPointF(x, endY));

    // 创建线项
    m_lineItem = createLineItem(startScene, endScene);
    addDrawingItem(m_lineItem);

    // 初始信号触发
    onLinePositionChanged();
}

QVariantMap VerticalSingleLineDrawer::getMeasurementResult() const
{
    if (!m_lineItem) {
        qWarning() << "线项未设置，无法获取测量结果";
        return QVariantMap();
    }

    QVariantMap result;
    QLineF lineScene = m_lineItem->line();
    
    // 转换为图像像素坐标
    QPointF startImage = sceneToImageCoordinates(lineScene.p1());
    QPointF endImage = sceneToImageCoordinates(lineScene.p2());
    
    QLineF lineImage(startImage, endImage);

    // 计算线的长度（像素）
    qreal length = lineImage.length();
    result.insert("length", length);

    // 存储线的位置信息（图像坐标）
    result.insert("x_position", lineImage.x1());
    result.insert("start_y", lineImage.y1());
    result.insert("end_y", lineImage.y2());

    // 存储测量模式
    result.insert("measurement_mode", static_cast<int>(MeasurementMode::VerticalSingleLine));

    // 收集线上的点（图像坐标，用于灰度值测量）
    QList<QPointF> points;
    int pointCount = qMax(10, static_cast<int>(length / 5)); // 至少10个点，每5像素一个点
    
    for (int i = 0; i < pointCount; ++i) {
        qreal ratio = static_cast<qreal>(i) / (pointCount - 1);
        qreal y = lineImage.y1() + (lineImage.y2() - lineImage.y1()) * ratio;
        qreal x = lineImage.x1();
        points.append(QPointF(x, y));
    }
    
    result.insert("points", QVariant::fromValue(points));

    return result;
}

void VerticalSingleLineDrawer::clearAll()
{
    removeAllItems();
    m_lineItem = nullptr;
    m_drawingItems.clear();
}

MeasurementMode VerticalSingleLineDrawer::getMeasurementMode() const
{
    return MeasurementMode::VerticalSingleLine;
}

void VerticalSingleLineDrawer::restoreFromResult(const QVariantMap &result, double scale, const QPointF &offset)
{
    if (!m_scene || !result.contains("x_position") || !result.contains("start_y") || !result.contains("end_y")) {
        qWarning() << "结果数据不完整，无法恢复绘制";
        return;
    }

    // 更新缩放和偏移信息
    m_scale = scale;
    m_offset = offset;

    // 清除之前的绘制项
    removeAllItems();

    // 从结果中提取线信息（图像坐标）
    qreal x = result.value("x_position").toDouble();
    qreal startY = result.value("start_y").toDouble();
    qreal endY = result.value("end_y").toDouble();

    // 转换为场景坐标
    QPointF startScene = imageToSceneCoordinates(QPointF(x, startY));
    QPointF endScene = imageToSceneCoordinates(QPointF(x, endY));
    
    // 创建线项
    m_lineItem = createLineItem(startScene, endScene);
    addDrawingItem(m_lineItem);
    
    // 触发位置变化信号
    onLinePositionChanged();
}

void VerticalSingleLineDrawer::setParameters(const QVariantMap &params)
{
    // 更新线宽
    if (params.contains("line_width")) {
        m_lineWidth = params.value("line_width").toInt();
    }

    // 更新线颜色
    if (params.contains("line_color")) {
        m_lineColor = params.value("line_color").value<QColor>();
    }
    
    // 更新画笔
    m_linePen = QPen(m_lineColor, m_lineWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
    
    // 如果已有线项，更新其样式
    if (m_lineItem) {
        m_lineItem->setPen(m_linePen);
    }
}

void VerticalSingleLineDrawer::updateTransformInfo(double scale, const QPointF &offset)
{
    if (m_scale == scale && m_offset == offset) {
        return; // 没有变化，不需要更新
    }
    
    // 保存当前图像坐标（基于旧的缩放和偏移）
    QPointF startImage, endImage;
    bool hasLine = m_lineItem != nullptr;
    if (hasLine) {
        QLineF lineScene = m_lineItem->line();
        startImage = sceneToImageCoordinates(lineScene.p1());
        endImage = sceneToImageCoordinates(lineScene.p2());
    }
    
    // 更新缩放和偏移
    m_scale = scale;
    m_offset = offset;
    
    // 使用新的缩放和偏移将图像坐标转换回场景坐标
    if (hasLine) {
        QPointF newStartScene = imageToSceneCoordinates(startImage);
        QPointF newEndScene = imageToSceneCoordinates(endImage);
        
        // 更新线的位置
        m_lineItem->setLine(QLineF(newStartScene, newEndScene));
    }
}

void VerticalSingleLineDrawer::setScale(double scale)
{
    // 调用updateTransformInfo方法，保持偏移不变，只更新缩放
    updateTransformInfo(scale, m_offset);
}

QPointF VerticalSingleLineDrawer::sceneToImageCoordinates(const QPointF &scenePos) const
{
    // 场景坐标 -> 图像像素坐标
    // 图像的0,0坐标对应场景中的偏移坐标
    QPointF imagePos;
    imagePos.setX((scenePos.x() - m_offset.x()) / m_scale);
    imagePos.setY((scenePos.y() - m_offset.y()) / m_scale);
    return imagePos;
}

QPointF VerticalSingleLineDrawer::imageToSceneCoordinates(const QPointF &imagePos) const
{
    // 图像像素坐标 -> 场景坐标
    // 图像的0,0坐标对应场景中的偏移坐标，图像的100,100坐标等于100*m_scale + m_offset
    QPointF scenePos;
    scenePos.setX(imagePos.x() * m_scale + m_offset.x());
    scenePos.setY(imagePos.y() * m_scale + m_offset.y());
    return scenePos;
}

void VerticalSingleLineDrawer::onLinePositionChanged()
{
    if (!m_lineItem) {
        return;
    }
    
    // 获取场景坐标中的线
    QLineF lineScene = m_lineItem->line();
    
    // 转换为图像像素坐标
    QPointF startImage = sceneToImageCoordinates(lineScene.p1());
    QPointF endImage = sceneToImageCoordinates(lineScene.p2());
    
    QLineF lineImage(startImage, endImage);
    
    // 发送信号，上报图像像素坐标
    emit lineChanged(lineImage);
}

DraggableLineItem *VerticalSingleLineDrawer::createLineItem(const QPointF &start, const QPointF &end)
{
    DraggableLineItem *lineItem = new DraggableLineItem(QLineF(start, end));
    lineItem->setPen(m_linePen);
    lineItem->setVertical(true); // 设置为垂直线
    
    // 连接位置变化信号
    connect(lineItem, &DraggableLineItem::positionChanged, this, &VerticalSingleLineDrawer::onLinePositionChanged);
    
    return lineItem;
}

void VerticalSingleLineDrawer::initializeStyles()
{
    // 设置默认样式
    m_lineWidth = 2;
    m_lineColor = Qt::blue;

    // 初始化画笔
    m_linePen = QPen(m_lineColor, m_lineWidth, Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin);
}

void VerticalSingleLineDrawer::addDrawingItem(QGraphicsItem *item)
{
    if (m_scene && item) {
        // 设置zValue大于图像项的zValue(0)，确保绘制项显示在图像上方
        item->setZValue(1);
        m_scene->addItem(item);
        m_drawingItems.append(item);
    }
}

void VerticalSingleLineDrawer::removeAllItems()
{
    if (m_scene) {
        for (QGraphicsItem *item : m_drawingItems) {
            m_scene->removeItem(item);
            delete item;
        }
    }
    m_drawingItems.clear();
}
